package breeze.lepei.der.loginview.presenter;
import android.app.ActivityOptions;
import android.content.Context;
import android.content.Intent;
import breeze.lepei.der.BaseView;
import breeze.lepei.der.lepei.LepeiApiUti;
import breeze.lepei.der.loginview.view.ILoginView;
import breeze.lepei.der.loginview.view.LoginView;
import breeze.lepei.der.logo_view.view.LogoView;
import breeze.lepei.der.main_view.view.MainView;
import breeze.lepei.der.usersettings.UserSettings;
import breeze.lepei.der.utils.AppTools;
import breeze.lepei.der.utils.MLog;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import java.io.IOException;
import org.json.JSONException;
import org.json.JSONObject;

public class LoginPresenter implements ILoginPresenter {

	/**
	*@author BREEZE
	*@description 登录
	*@param 手机号/密码
	*/
	@Override
	public void login(final String phone, final String password) {
		final String link=LepeiApiUti.login(phone,password);
		Observable<String> obs=Observable.create(new ObservableOnSubscribe<String>(){
				@Override
				public void subscribe(final ObservableEmitter<String> p1) throws Exception {
					BaseView.getExec().execute(new Runnable(){public void run(){
								try {
									String json=AppTools.getWebContent(link);
									p1.onNext(json);
								} catch (IOException e) {
									p1.onError(e);
									MLog.logE("LoginPresenter",e);
								}
					}});
				}
		});
		Observer<String> server=new Observer<String>(){

			@Override
			public void onComplete() {
			}

			@Override
			public void onError(Throwable p1) {
				loginview.stopLoading();
				loginview.showDialog(p1.toString());
			}

			@Override
			public void onNext(String p1) {
				MLog.log("登录结果",p1);
				try {
					JSONObject obj=new JSONObject(p1);
					int code=obj.getInt("code");
					String msg=obj.getString("msg");
					if(code!=200){
						loginview.showDialog(msg);
					}else{
						//TODO：登录成功保存数据
						JSONObject obj2=obj.getJSONObject("obj");
						String token=obj2.getString("token");
						String vi=obj2.getString("vi");
						UserSettings usersettings=UserSettings.getInstance(mContext);
						usersettings.setUserPhone(phone);
						usersettings.setUserPass(password);
						usersettings.setToken(token);
						usersettings.setVi(vi);
						loginview.jumpView();
					}
				} catch (JSONException e) {
					MLog.logE(TAG,e);
				}
			}

			@Override
			public void onSubscribe(Disposable p1) {
			}
		};
		obs.subscribe(server);
	}
    
	private ILoginView loginview;
	private Context mContext;
	private static String TAG="LoginPresenter";
	
    public LoginPresenter(LoginView view){
		this.mContext=view.getApplicationContext();
		this.loginview=view;
	}
}
